/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.parameter.controller;

import com.wallellen.core.page.OperateType;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DBSort;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.parameter.domain.AloneDictionaryType;
import com.wallellen.parameter.service.DictionaryTypeServiceInter;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiTreeNode;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by walle on 12/12/15.
 */

@RequestMapping({"/dictionaryType"})
@Controller
public class DictionaryTypeController extends WebUtils {
    private String parentName;
    private static final Logger log = LoggerFactory.getLogger(DictionaryTypeController.class);

    @Resource
    DictionaryTypeServiceInter dictionaryTypeServiceImpl;

    @RequestMapping({"/query"})
    @ResponseBody
    public Map<String, Object> queryall(DataQuery query, HttpServletRequest request, String ids) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            query =
                    DataQuery.init(
                            query,
                            "alone_dictionary_type a LEFT JOIN alone_dictionary_type b ON a.parentid = b.id",
                            "a.id AS ID,a.sort AS SORT,a.name AS NAME,a.entitytype AS ENTITYTYPE,a.state AS STATE,b.name AS PNAME");
            query.addSqlRule(" and (a.state = '0' or a.state = '1') ");
            query.addDefaultSort(new DBSort("a.sort", "asc"));
            if ((ids != null) && (ids.trim().length() > 0)) {
                query.addRule(new DBRule("a.entity", ids, "="));
            }
            DataResult result = query.search();
            result.runDictionary("1:可用,0:禁用", "STATE");
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(result))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/edit"})
    @ResponseBody
    public Map<String, Object> editSubmit(AloneDictionaryType dictionary, HttpSession session) {
        try {
            AloneDictionaryType entity = this.dictionaryTypeServiceImpl.editEntity(dictionary, getCurrentUser(session));
            return ViewMode.getInstance().putAttr("entity", entity)
                    .returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public Map<String, Object> addSubmit(AloneDictionaryType dictionary, HttpSession session) {
        try {
            AloneDictionaryType entity = this.dictionaryTypeServiceImpl.insertEntity(dictionary, getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/del"})
    @ResponseBody
    public Map<String, Object> delSubmit(String ids, HttpSession session) {
        try {
            for (String id : parseIds(ids)) {
                if (this.dictionaryTypeServiceImpl.getEntity(id) != null) {
                    this.dictionaryTypeServiceImpl.deleteEntity(id, getCurrentUser(session));
                }
            }
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/ALONEDictionaryType_ACTION_CONSOLE"})
    public ModelAndView forSend(String ids, String type) {
        if ("0".equals(type)) {
            return ViewMode.getInstance()
                    .putAttr("ids", ids)
                    .putAttr("type", type)
                    .returnModelAndView("parameter/pAloneDictionaryTypeTreeLayout");
        }

        return ViewMode.getInstance()
                .putAttr("ids", ids)
                .putAttr("type", type)
                .returnModelAndView("parameter/pAloneDictionaryTypeLayout");
    }

    @RequestMapping({"/form"})
    public ModelAndView view(RequestMode pageset, String ids, String dicId) {
        try {
            switch (pageset.getOperateType()) {
                case 1:
                    if ((dicId == null) || (dicId.equals(""))) {
                        throw new RuntimeException("找不到关联的数据字典！");
                    }
                    AloneDictionaryType entity = new AloneDictionaryType();
                    entity.setEntity(dicId);

                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .returnModelAndView("parameter/pAloneDictionaryTypeEntity");
                case 0:
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", this.dictionaryTypeServiceImpl.getEntity(ids))
                            .returnModelAndView("parameter/pAloneDictionaryTypeEntity");
                case 2:
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", this.dictionaryTypeServiceImpl.getEntity(ids))
                            .returnModelAndView("parameter/pAloneDictionaryTypeEntity");
            }

        } catch (Exception e) {
            return ViewMode.getInstance().setError(e + e.getMessage())
                    .returnModelAndView("parameter/pAloneDictionaryEntityEntity");
        }
        return ViewMode.getInstance().returnModelAndView(
                "parameter/pAloneDictionaryEntityEntity");
    }

    @RequestMapping({"/viewTreeform"})
    public ModelAndView viewTree(RequestMode pageset, String ids, String dicId, String parentId) {
        try {
            AloneDictionaryType entity = null;
            switch (pageset.getOperateType()) {
                case 1:
                    if ((dicId == null) || (dicId.equals(""))) {
                        throw new RuntimeException("找不到关联的数据字典！");
                    }
                    entity = new AloneDictionaryType();
                    entity.setEntity(dicId);
                    if ((parentId != null) && (!parentId.equals(""))) {
                        AloneDictionaryType pEntity = this.dictionaryTypeServiceImpl.getEntity(parentId);
                        if (pEntity.getState().equals("1")) {
                            this.parentName = pEntity.getName();
                            entity.setParentid(parentId);
                        }
                    } else {
                        entity.setParentid("NONE");
                    }
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .putAttr("parentName", this.parentName)
                            .returnModelAndView("parameter/pAloneDictionaryTypeTreeEntity");
                case 0:
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", this.dictionaryTypeServiceImpl.getEntity(ids))
                            .returnModelAndView("parameter/pAloneDictionaryTypeTreeEntity");
                case 2:
                    entity = this.dictionaryTypeServiceImpl.getEntity(ids);
                    if (!entity.getParentid().equals("NONE")) {
                        this.parentName = this.dictionaryTypeServiceImpl.getEntity(entity.getParentid())
                                .getName();
                    }

                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .putAttr("parentName", this.parentName)
                            .returnModelAndView("parameter/pAloneDictionaryTypeTreeEntity");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e + e.getMessage())
                    .returnModelAndView("parameter/pAloneDictionaryTypeTreeEntity");
        }
        return ViewMode.getInstance().returnModelAndView(
                "parameter/pAloneDictionaryTypeTreeEntity");
    }

    @RequestMapping({"/dictionaryTreeNote"})
    @ResponseBody
    public Object loadTreeNode(String ids, String id) {
        if (id == null)
            id = "NONE";
        try {
            return
                    EasyUiTreeNode.formatAsyncAjaxTree(
                            EasyUiTreeNode.queryTreeNodeOne(
                                    id,
                                    "SORT",
                                    " (SELECT a.id AS ID,a.parentid AS PARENTID,a.name AS NAME,a.ctime AS CTIME,a.sort AS SORT,a.entity AS ENTITY,a.state AS STATE FROM ALONE_DICTIONARY_TYPE a LEFT JOIN ALONE_DICTIONARY_ENTITY b ON a.ENTITY = b.id  WHERE b.type = 0) ",
                                    "ID",
                                    "PARENTID",
                                    "NAME",
                                    "CTIME",
                                    " and a.ENTITY='" + ids +
                                            "' and a.state!=2")
                                    .getResultList(),
                            EasyUiTreeNode.queryTreeNodeTow(
                                    id,
                                    "SORT",
                                    " (SELECT a.id AS ID,a.parentid AS PARENTID,a.name AS NAME,a.ctime AS CTIME,a.sort AS SORT,a.entity AS ENTITY,a.state AS STATE FROM ALONE_DICTIONARY_TYPE a LEFT JOIN ALONE_DICTIONARY_ENTITY b ON a.ENTITY = b.id  WHERE b.type = 0) ",
                                    "ID",
                                    "PARENTID",
                                    "NAME",
                                    "CTIME",
                                    " and a.ENTITY='" + ids +
                                            "' and a.state!=2")
                                    .getResultList(), "PARENTID", "ID", "NAME",
                            "CTIME");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }
}